package BESA.Mobile.Directory;

import BESA.ExceptionBESA;
import BESA.Kernell.Agent.Event.EventBESA;
import BESA.Kernell.System.AdmBESA;
import BESA.Kernell.System.Directory.AgHandlerBESA;
import BESA.PostOffice.Message.EventMessage_BPO;
import BESA.PostOffice.Message.MessageFactory_BPO;
import BESA.PostOffice.PostOffice_BPO;

/**
 *
 * @author Andrea Barraza
 */
/*
 * REVISAR: Falta que cuando falle el sendEvent y reciba un NACK pq no existe el
 * agente o algo asi se vuelva intentar localizar el agente y enviar el mensaje
 * bajo el mismo timeout q se tenia
 */
public class AgMobilelHandlerBESA extends AgHandlerBESA {

    private String containerID;

    public AgMobilelHandlerBESA(String agId, String alias, String containerID) {
        super(agId, alias);
        this.containerID = containerID;
    }

    public synchronized void sendEvent(EventBESA event, int timeOut) throws ExceptionBESA {
        sendEventAux(event, timeOut);
    }

    @Override
    public synchronized void sendEvent(EventBESA event) throws ExceptionBESA {
        sendEventAux(event, (int) (AdmBESA.getInstance().getConfigBESA()).getSendEventTimeout());
    }

    private synchronized void sendEventAux(EventBESA event, int timeOut) throws ExceptionBESA {
        try {
            //Send Message
            EventMessage_BPO message = MessageFactory_BPO.createEventMessage(this.getAgId(), event);
            PostOffice_BPO.get().sendMessageToLocation(containerID, message);
            message.waitForACK(timeOut);
            //Check if message timed out
            if (message.getACK() == null) {
                PostOffice_BPO.get().messageTimedOut(containerID, message);
                throw new ExceptionBESA("Message Timed-Out");
            } else //Verify Message State
            if (message.getACK().isNegative()) {
                throw new ExceptionBESA(message.getACK().getExceptionMessage());
            }
        } catch (InterruptedException ex) {
            throw new ExceptionBESA("[AgPostManHandler_BPO] InterruptedException");
        }
    }

    public String getLocation() {
        return containerID;
    }
}
